package com.wenchao.quickstart.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;

/**
 * @author zhangwenchao
 */
public class DeviceUtil {

    /**
     * 获取手机外部可用空间大小
     *
     * @return
     */
    public static String getAvailableExternalMemorySize(Context context) {
        if (isExternalStorageAvailable()) {
            StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return Formatter.formatFileSize(context, availableBlocks * blockSize);
        } else {
            return "-1";
        }
    }

    /**
     * 获取手机外部总空间大小
     *
     * @return
     */
    public static String getTotalExternalMemorySize(Context context) {
        if (isExternalStorageAvailable()) {
            StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return Formatter.formatFileSize(context, totalBlocks * blockSize);
        } else {
            return "-1";
        }
    }

    /**
     * 外部存储是否可用 (存在且具有读写权限)
     */
    public static boolean isExternalStorageAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取内存存储使用率
     *
     * @return
     */
    public static int getInternalStorageUsedPercent() {
        return (int) (getAvailableInternalMemorySize() * 100 / getTotalInternalMemorySize());
    }

    /**
     * 获取手机内部可用空间大小
     *
     * @return
     */
    static public String getAvailableInternalMemory(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, availableBlocks * blockSize);
    }

    /**
     * 获取手机内部可用空间大小
     *
     * @return
     */
    static public long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 获取手机内部空间大小
     *
     * @return
     */
    public static String getTotalInternalMemory(Context context) {
        // Gets the Android data directory
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        // 每个block 占字节数
        long blockSize = stat.getBlockSize();
        // block总数
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, totalBlocks * blockSize);
    }

    /**
     * 获取手机内部空间大小
     *
     * @return
     */
    public static long getTotalInternalMemorySize() {
        // Gets the Android data directory
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        // 每个block 占字节数
        long blockSize = stat.getBlockSize();
        // block总数
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 内存使用率
     *
     * @param activity
     * @return
     */
    public static int getMemoryUsedPercent(Activity activity) {
        if (null == activity) {
            return 0;
        }
        return (int) (getAvailMemorySize(activity) * 100 / getTotalMemorySize());
    }

    /**
     * 获取内存可用空间
     *
     * @return
     */
    public static long getAvailMemorySize(Activity activity) {
        // 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        // mi.availMem; 当前系统的可用内存
        // 将获取的内存大小规格化
        return mi.availMem;
    }

    /**
     * 获取内存可用空间
     *
     * @return
     */
    public static String getAvailMemory(Activity activity) {
        // 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        // mi.availMem; 当前系统的可用内存
        // 将获取的内存大小规格化
        return Formatter.formatFileSize(activity, mi.availMem);
    }

    /**
     * 获取内存总共空间
     *
     * @return
     */
    public static long getTotalMemorySize() {
        // 系统内存信息文件
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initialMemory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            // 读取meminfo第一行，系统总内存大小
            str2 = localBufferedReader.readLine();

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.e(str2, num + "\t");
            }
            // 获得系统总内存，单位是KB，乘以1024转换为Byte
            initialMemory = Long.parseLong(arrayOfString[1]) * 1024;
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Byte转换为KB或者MB，内存大小规格化
        return initialMemory;
    }

    /**
     * 获取内存总共空间
     *
     * @return
     */
    public static String getTotalMemory(Context context) {
        // 系统内存信息文件
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            // 读取meminfo第一行，系统总内存大小
            str2 = localBufferedReader.readLine();

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.e(str2, num + "\t");
            }
            // 获得系统总内存，单位是KB，乘以1024转换为Byte
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
            localBufferedReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        // Byte转换为KB或者MB，内存大小规格化
        return Formatter.formatFileSize(context, initial_memory);
    }

    /**
     * 获取cpu使用率
     *
     * @return
     */
    public static int getCpuUsedPercent() {
        return (int) getCpuUsed() * 100;
    }

    /**
     * 获取cpu使用率
     *
     * @return
     */
    public static float getCpuUsed() {
        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            String[] toks = load.split(" ");
            long idle1 = Long.parseLong(toks[5]);
            long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                    + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            try {
                Thread.sleep(360);
            } catch (Exception e) {
                e.printStackTrace();
            }
            reader.seek(0);
            load = reader.readLine();
            reader.close();
            toks = load.split(" ");
            long idle2 = Long.parseLong(toks[5]);
            long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                    + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取SN
     *
     * @return
     */
    public static String getDeviceSN() {
        String serial = "";
        //通过android.os获取sn号
        try {
            serial = android.os.Build.SERIAL;
            if (!serial.equals("") && !serial.equals("unknown")) {
                return serial;
            }
        } catch (Exception e) {
            serial = "";
        }

        //通过反射获取sn号
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
            if (!serial.equals("") && !serial.equals("unknown")) {
                return serial;
            }

            //9.0及以上无法获取到sn，此方法为补充，能够获取到多数高版本手机 sn
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            }
        } catch (Exception e) {
            serial = "";
        }
        return "".equals(serial) ? "unknown" : serial;
    }

    /**
     * 获取当前媒体的音量
     *
     * @param context
     * @return
     */
    public static int getCurrentMediaVol(Context context) {
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        return current * 100 / max;
    }

    public static void onVolAdd() {
        String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_UP;
        Runtime runtime = Runtime.getRuntime();
        try {
            Process proc = runtime.exec(keyCommand);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void onVolReduce() {
        String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_DOWN;
        Runtime runtime = Runtime.getRuntime();
        try {
            Process proc = runtime.exec(keyCommand);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void reboot(Context context) {
        ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .killBackgroundProcesses(context.getPackageName());
        try {
            Runtime.getRuntime().exec("su");
            Runtime.getRuntime().exec("reboot");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Bitmap onScreenShot(Activity activity) {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        return activity.getWindow().getDecorView().getDrawingCache();
    }

    public static String onScreenShot(Activity activity, String path) {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bitmap = activity.getWindow().getDecorView().getDrawingCache();
        // 将要保存图片的路径
        File file = new File(path + File.separator + "screenshot_" + System.currentTimeMillis() + ".png");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
